package web.servlet.list.web;

import org.apache.commons.beanutils.BeanUtils;
import web.servlet.list.dao.UserDao;
import web.servlet.list.dao.UserDaoImpl;
import web.servlet.list.domin.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2020/6/12 9:17
 **/
@WebServlet("/userAddServlet")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        UserDao dao = new UserDaoImpl();
        int i = dao.insert(user);
        if (i > 0) {
            String path = request.getContextPath();
            response.sendRedirect(path + "/userListServlet");
        } else if(i==0){
            request.setAttribute("add_error", "插入失败");
            request.getRequestDispatcher("/list/add.jsp").forward(request,response);
        }else  {
            request.setAttribute("add_error", "用户名重复");
            request.getRequestDispatcher("/list/add.jsp").forward(request,response);
        }

    }
}
